//Given an integer array nums and an integer k, return the k most frequent 
//elements. You may return the answer in any order. 
//
// 
// Example 1: 
// Input: nums = [1,1,1,2,2,3], k = 2
//Output: [1,2]
// Example 2: 
// Input: nums = [1], k = 1
//Output: [1]
// 
// 
// Constraints: 
//
// 
// 1 <= nums.length <= 10⁵ 
// k is in the range [1, the number of unique elements in the array]. 
// It is guaranteed that the answer is unique. 
// 
//
// 
// Follow up: Your algorithm's time complexity must be better than O(n log n), 
//where n is the array's size. 
// Related Topics Array Hash Table Divide and Conquer Sorting Heap (Priority 
//Queue) Bucket Sort Counting Quickselect 👍 6277 👎 302


package leetcode.editor.en;

import java.util.Comparator;
import java.util.HashMap;
import java.util.Map;
import java.util.PriorityQueue;

public class _347_TopKFrequentElements {
    public static void main(String[] args) {
        Solution solution = new _347_TopKFrequentElements().new Solution();
        int[] ints = solution.topKFrequent(new int[]{4,1,-1,2,-1,2,3}, 2);
    }

    //leetcode submit region begin(Prohibit modification and deletion)
    class Solution {
        public int[] topKFrequent(int[] nums, int k) {
            Map<Integer, Integer> map = new HashMap<>();
            for (int num : nums) {
                Integer orDefault = map.getOrDefault(num, 0);
                map.put(num, orDefault+1);
            }
            PriorityQueue<Integer> priorityQueue = new PriorityQueue<>(Comparator.comparingInt(map::get));
            for (int num : map.keySet()) {
                if (priorityQueue.size()<k) {
                    priorityQueue.add(num);
                }else if (map.get(priorityQueue.peek())<map.get(num)){
                    priorityQueue.remove();
                    priorityQueue.offer(num);
                }
            }
            int[] r = new int[k];
            for (int i = 0; i < k; i++) {
                r[i] = priorityQueue.poll();
            }
            return r;
        }
    }
//leetcode submit region end(Prohibit modification and deletion)

}